<?php
namespace app\service;

use PhpMqtt\Client\MqttClient;
use PhpMqtt\Client\ConnectionSettings;

class MqttService
{
    protected $client;

    public function __construct()
    {
        $server   = '220.166.79.246'; // MQTT 服务器地址
        $port     = 10037;               // MQTT 服务器端口
        $clientId = 'api_local_core';  // 客户端 ID
        $username = 'localuser';    // 用户名（如果有）
        $password = 'localuser_new';    // 密码（如果有）

        $this->client = new MqttClient($server, $port, $clientId);

        $connectionSettings = (new ConnectionSettings())
            ->setUsername($username)
            ->setPassword($password);

        $this->client->connect($connectionSettings, true);
    }

    public function publish($topic, $message,$qos=0)
    {

        $this->client->publish($topic, $message,$qos);
    }

    public function subscribe($topic, $callback)
    {
        $this->client->subscribe($topic, $callback);
    }

    public function disconnect()
    {
        $this->client->disconnect();
    }
}